package com.cuckoo.cuckoo_app2.ui;

import android.app.AlertDialog;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import com.cuckoo.cuckoo_app2.MyApplication;
import com.cuckoo.cuckoo_app2.R;
import com.cuckoo.cuckoo_app2.model.IntentResponseModel;
import com.cuckoo.cuckoo_app2.service.MyBackgroundService;
import com.cuckoo.cuckoo_app2.utils.DialogUtils;
import com.cuckoo.cuckoo_app2.utils.LocalBroadCodeUtils;
import com.cuckoo.cuckoo_app2.utils.NotificationUtils;
import com.cuckoo.cuckoo_app2.utils.RouteUtils;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.NavigationUI;

import android.util.Log;

public class MainActivity extends AppCompatActivity {

    private BottomNavigationView navView;
    private NavController navController;
    private Context context;
    private NotificationUtils notificationUtils;

    /**
     * 通讯回调
     */
    private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context c, Intent intent) {
            String action = intent.getAction();
            Log.i("LocalBroadcastReceiver", action);
            IntentResponseModel model = (IntentResponseModel) intent.getSerializableExtra("model");

            switch (action) {
                case LocalBroadCodeUtils.LOCAL_BROADCAST_UPDATE_APP:
                    String url = model.getValue().toString();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            DialogUtils.showMessageDialog(context, "更新提示", "检测到新版本，请前往更新！", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                                    startActivity(intent);
                                    DialogUtils.hideCurrentDialog();
                                    System.exit(0);
                                }
                            });
                        }
                    });
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("TEST", "MainActivity.onCreate()");
        setContentView(R.layout.activity_main);
        this.context = this;
        this.notificationUtils = new NotificationUtils(this);

        this.initView();
        this.setNavigationView();
        this.initServer();

    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i("TEST", "MainActivity.onStart()");
        // 检测权限
        this.checkPermission();

        // 检查用户是否已登录
        if (MyApplication.getInstances().getUser() == null) {
            RouteUtils.toLoginActivity(this);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i("TEST", "MainActivity.onResume()");

        // 注册BroadcastReceiver以接收广告广播
        IntentFilter intentFilter = new IntentFilter();
        // 跳转登录页面
        intentFilter.addAction(LocalBroadCodeUtils.LOCAL_BROADCAST_UPDATE_APP);
        LocalBroadcastManager.getInstance(this).registerReceiver(myBroadcastReceiver, intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i("TEST", "MainActivity.onPause()");
        // 注销BroadcastReceiver
        LocalBroadcastManager.getInstance(this).unregisterReceiver(myBroadcastReceiver);
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i("TEST", "MainActivity.onStop()");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i("TEST", "MainActivity.onDestroy()");
        Intent stopIntent = new Intent(this, MyBackgroundService.class);
        stopService(stopIntent);
    }

    public void initView() {
        navView = findViewById(R.id.nav_view);
        navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupWithNavController(navView, navController);
    }

    public void initServer() {
        Intent intent = new Intent(this, MyBackgroundService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent);
        } else {
            startService(intent);
        }
    }

    /**
     * 设置菜单栏
     */
    private void setNavigationView() {
        // 绑定事件
        if (navView == null) {
            return;
        }
        navView.setItemIconTintList(null);

        int[] unselectedIcons = {R.drawable.ic_home, R.drawable.ic_list, R.drawable.ic_messages, R.drawable.ic_profile};
        int[] selectedIcons = {R.drawable.ic_home_on, R.drawable.ic_list_on, R.drawable.ic_messages_on, R.drawable.ic_profile_on};
        int[] tableNames = {R.string.app_name, R.string.title_list, R.string.title_messages, R.string.title_profile};

        // 初始设置所有菜单项的图标为未选中状态
        for (int i = 0; i < navView.getMenu().size(); i++) {
            MenuItem menuItem = navView.getMenu().getItem(i);
            menuItem.setIcon(unselectedIcons[i]);
        }

        // 默认选中第一个菜单项（可选）
        int defaultPage = 0;
        Menu menu = navView.getMenu();
        if (menu != null && menu.size() > 0) {
            MenuItem item = menu.getItem(defaultPage);
            item.setChecked(true);
            item.setIcon(selectedIcons[defaultPage]);
            setTitle(tableNames[defaultPage]);
        }

        navView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                Menu menu = navView.getMenu();
                // 切换图标
                for (int i = 0; i < menu.size(); i++) {
                    MenuItem menuItem = menu.getItem(i);
                    if (menuItem.getItemId() == item.getItemId()) {
                        // 如果该项被选中，则设置选中状态的图标
                        menuItem.setIcon(selectedIcons[i]);
                        setTitle(tableNames[i]);
                    } else {
                        // 如果该项未被选中，则设置未选中状态的图标
                        menuItem.setIcon(unselectedIcons[i]);
                    }
                }

                // 可以在这里处理Fragment的切换等逻辑
                if (item.getItemId() == R.id.fragment_home) {
                    Log.i("TEST", "R.id.fragment_home");

                } else if (item.getItemId() == R.id.fragment_dashboard) {
                    Log.i("TEST", "R.id.fragment_dashboard");

                } else if (item.getItemId() == R.id.fragment_notifications) {
                    Log.i("TEST", "R.id.fragment_notifications");

                } else if (item.getItemId() == R.id.fragment_profile) {
                    Log.i("TEST", "R.id.fragment_profile");

                }

                // 调用 NavController 来导航到所选目的地
                boolean handled = NavigationUI.onNavDestinationSelected(item, navController);
                return handled;
            }
        });
    }

    /**
     * 检测权限是否开启
     */
    public void checkPermission() {
        // 发送通知
        if (notificationUtils != null && MyApplication.getInstances().getUser() != null) {
            notificationUtils.checkAndPromptNotificationPermission();
        }
    }

}